﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using jSLApp.Client.ApplicationBase;
using jSLApp.Client.MainService;
using jSLCore.Client.Presentation.AuthorizeService;
using jSLCore.Client.Presentation.BaseControl;
using jSLCore.Client.Presentation.BaseControl.Selection;
using jSLCore.Client.Presentation.jBinding.BaseConverters;
using jSLCore.Client.Presentation.Util;
using jSLCore.Client.Utility;

namespace jSLApp.Client.Forms
{
// ReSharper disable RedundantExtendsListEntry
    public partial class StartPage : DataControl
// ReSharper restore RedundantExtendsListEntry
    {
        public StartPage()
        {
            InitializeComponent();
        }

        MainServiceClient posterLoaderClient;

        public override void LoadInitialData()
        {
                LoadFavorites();
        }
        
        private void LoadPoster(Film film)
        {

            posterLoading.IsBusy = true;

            if (posterLoaderClient != null) posterLoaderClient.Abort();

            var basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.None)
            {
                MaxBufferSize = 2147483647,
                MaxReceivedMessageSize = 2147483647,
                SendTimeout = new TimeSpan(1, 0, 0, 0),
                ReceiveTimeout = new TimeSpan(1, 0, 0, 0),
                TransferMode = TransferMode.StreamedResponse
            };
            var address = new EndpointAddress(new Uri(UIHelper.GetCurrentWebHostAddress() + "MainService.svc"));

            posterLoaderClient = new MainServiceClient(basicHttpBinding,address);

            posterLoaderClient.GetFilmLastPhotoCompleted += (sender1, completedEventArgs) =>
                                                                {
                                                                    if (completedEventArgs.Error == null)
                                                                    {
                                                                        var poster = completedEventArgs.Result;

                                                                        if (poster != null)
                                                                        {
                                                                            film.PosterCash = new Binary
                                                                                                  {
                                                                                                      Bytes =
                                                                                                          poster
                                                                                                  };

                                                                            if (favoriteFilms.SelectedItem == film)
                                                                                SetPoster(poster);
                                                                        }

                                                                    }
                                                                    posterLoading.IsBusy = false;
                                                                };

            posterLoaderClient.GetFilmLastPhotoAsync(film.id);

/*
            DoWork(true,(sender, args) =>
                                              {
                                                  args.Result = Communication.Proxy.GetFilmLastPhoto(args.Int);
                                              },(o, eventArgs) =>
                                                                    {
                                                                        if(eventArgs.Error==null)
                                                                        {
                                                                           
                                                                        }
                                                                        
                                                                    },film.id);*/
        }

        private void SetPoster(byte[] poster)
        {
            var converter = new jImageSourceConverter();

            filmPoster.Content =
                                                                                converter.Convert(poster,
                                                                                                  typeof(ImageSource),
                                                                                                  null, null);
        }

        private void LoadFavorites()
        {
            Debug.WriteLine("Вызвана загрузка фильмов");

            DoWork("Загрузка фильмов"
                   ,(sender, args) =>
                        {
                            args.Result = Communication.Proxy.GetTopFilms();
                        },(o, eventArgs) =>
                              {
                                  if(eventArgs.Error==null)
                                  {
                                      var itemsSource = (IEnumerable<Film>) eventArgs.Result;
                                      favoriteFilms.ItemsSource = itemsSource;
                                      var selectedFilm = itemsSource.SingleOrDefault(f=>f.IsSelected);

                                      if(selectedFilm!=null)
                                      {
                                          favoriteFilms.SelectedItem = selectedFilm;
                                      }
                                      else
                                      {
                                          var count = itemsSource.Count();
                                          favoriteFilms.SelectedIndex = count/2;
                                      }
                                  }
                              });
        }

        private void provideSelectedFilm_Clicked(object sender, RoutedEventArgs e)
        {
            var dlg = new FilmList(){SelectionMode = GridSelectionMode.SingleRow};

            dlg.ShowDialog(delegate(object o, object data)
                               {
                                   var film = (Film)data;

                                   DoWork("Установка избранного фильма",(sender1, args) => Communication.Proxy.SetSelectedFilm(args.Int),(o1, eventArgs) =>
                                                                                                   {
                                                                                                       if(eventArgs.Error==null)
                                                                                                       {
                                                                                                           //LoadSelectedFilm();
                                                                                                           selFilm.
                                                                                                               Content =
                                                                                                               film;
                                                                                                       LoadPoster(film);
                                                                                                           //LoadInitialData();
                                                                                                       }
                                                                                                   },film.id);
                               });
        }

        private void goSelFilm_Clicked(object sender, RoutedEventArgs e)
        {
            GotoFilmFromDataContext(sender);
        }

        private void GotoFilmFromDataContext(object sender)
        {
            var element = (FrameworkElement)sender;
            var film = (Film)element.DataContext;
            MainContentContainer.Current.ShowFilm(film.id);
        }

        private void selFilm_Changed(object sender, SelectionChangedEventArgs e)
        {
            var selfilm = (Film)favoriteFilms.SelectedItem;

            if (selfilm != null)
            {
                var superWorker = GetSuperWorker();

                superWorker.OperationQueue.Clear();

                
                    if (selfilm.SmallCover != null)
                        if (selfilm.BigImage == null || selfilm.BigImage.Bytes.Length == selfilm.SmallCover.Bytes.Length)
                        {
                            LoadBigCover(selfilm);
                        }

                if(selfilm.PosterCash==null)
                    LoadPoster(selfilm);
                else
                {
                    SetPoster(selfilm.PosterCash.Bytes);
                }

                selFilm.Content = selfilm;
            }
        }

        private void LoadBigCover(Film film)
        {
            DoWork(true,(sender, args) =>
                            {
                                args.Result = Communication.Proxy.GetBigCover(args.Int);
                            },(o, eventArgs) =>
                                  {
                                      if(eventArgs.Error==null)
                                      {
                                          film.BigImage = new Binary {Bytes = (byte[]) eventArgs.Result};
                                      }
                                  },film.id);
        }

        private void goPrev_Clicked(object sender, MouseButtonEventArgs e)
        {
            if(favoriteFilms.SelectedIndex>0)
                favoriteFilms.SelectedIndex--;
        }

        private void goNext_Clicked(object sender, MouseButtonEventArgs e)
        {
            if (((IEnumerable<Film>)favoriteFilms.ItemsSource).Count() > favoriteFilms.SelectedIndex+1)
                favoriteFilms.SelectedIndex++;
        }

        private void selFilmPanel_Clicked(object sender, MouseButtonEventArgs e)
        {
            GotoFilmFromDataContext(sender);
        }
    }
}
